﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Compilation;
using System.Web.UI;
using XTeam.Core.Interface;

namespace XTeam.Core.Helper
{
    public class AscxView : System.Web.UI.UserControl, IAscxView
    {

        public object Model
        {
            get;
            set;
        }

        public dynamic ViewBag
        {
            get;
            set;
        }

        public IDictionary<string, object> ViewData
        {
            get;
            set;
        }

    }


    public class AscxView<T> : AscxView, IAscxView<T>
    {
        public new T Model
        {
            get { return (T)base.Model; }
            set { base.Model = value; }
        }

    }


    public abstract class AscxHttpHandler : Page
    {
        private string _ascxPath = string.Empty;

        public dynamic ViewBag { get; set; }

        public IDictionary<string, object> ViewData { get; set; }

        public void View(string ascxPath)
        {
            this.View(ascxPath, null);
        }

        protected string Render(string ascxPath, object model)
        {
            Control control = this.LoadControl(ascxPath);
            if (control is IAscxView)
            {
                var view = (control as IAscxView);
                view.Model = model;
                view.ViewBag = this.ViewBag;
                view.ViewData = this.ViewData;

            }
            this.Controls.Add(control);
            StringWriter outPut = new StringWriter();
            this.Server.Execute(this, outPut, true);
            return outPut.ToString();

        }

        public void View(string ascxPath, object model)
        {
            Response.ContentType = "text/html";
            Response.Write(this.Render(ascxPath, model));
        }

        public static string Render(string ascxPath, object model = null
            , IDictionary<string, object> viewData = null
            , dynamic viewBag = null)
        {
            RenderAscxHandler handler = new RenderAscxHandler();
            handler.ViewData = viewData;
            handler.ViewBag = viewBag;
            return handler.Render(ascxPath, model);

        }

    }

    public class RenderAshxHandler
    {
        public static string Render(string ashxPath)
        {
            var handler = BuildManager.CreateInstanceFromVirtualPath(ashxPath, typeof(AscxHttpHandler)) as AscxHttpHandler;
            StringWriter outPut = new StringWriter();
            HttpContext.Current.Server.Execute(handler, outPut, false);
            return outPut.ToString();
        }
    }

    public class RenderAscxHandler : AscxHttpHandler
    {

    }

}
